package jwuo.serviceActivator;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Activator extends Activity
{
	Button bt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activator);
        bt = (Button) findViewById(R.id.button1);
		bt.setOnClickListener(new Button.OnClickListener()
		{
            public void onClick(View v) 
            {
            	try
            	{
            		boolean res = isMyServiceRunning();
            		if(!res)
            		{
            			Intent intent = new Intent();
                    	intent.setComponent(new ComponentName("jwuo.myServ", "jwuo.myServ.myService"));
                    	startService(intent);
                    	ShowMsg("The service was started succesfully!!");            			
            		}
            		else
            		{
            			ShowMsg("The service is already started!!"); 
            		}
            		
            		
            	}
            	catch(Exception e)
            	{
            		ShowMsg("Error: while startService- " + e.toString());
            	}
            	
            }
        });
    }
    
    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("jwuo.myServ.myService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    
    private void ShowMsg(String msg)
    {
    	int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(this, msg, duration);
		toast.show();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	menu.addSubMenu(0, 0, 0, "Exit");
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
    	int id = item.getItemId();
    	if(id==0)
    	{
    		this.finish();
    	}    	
    	return true;
    }

    
}
